package com.devo.icecream.utils

import android.annotation.SuppressLint
import java.util.*

class Time @JvmOverloads constructor(
    var hours: Int,
    var minus: Int,
    var seconds: Int = 0
) : Comparable<Time> {
    fun update(hours: Int, minus: Int, seconds: Int) {
        this.hours = hours
        this.minus = minus
        this.seconds = seconds
    }

    @SuppressLint("DefaultLocale")
    override fun toString(): String {
        return String.format("%02d:%02d", hours, minus)
    }

    override fun compareTo(other: Time): Int {
        if (equals(other)) {
            return 0
        } else if (hours > other.hours) {
            return 1
        } else if (hours == other.hours && minus > other.minus) {
            return 1
        } else if (hours == other.hours && minus == other.minus && seconds > other.seconds) {
            return 1
        }
        return -1
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || javaClass != other.javaClass) return false
        val time = other as Time
        return hours == time.hours && minus == time.minus && seconds == time.seconds
    }

    override fun hashCode(): Int {
        return Objects.hash(hours, minus, seconds)
    }

    companion object {
        @JvmOverloads
        fun parse(timeString: String, separator: String = ":"): Time {
            val strings = timeString.split(separator).toTypedArray()
            if (strings.size < 2) {
                throw RuntimeException("unresolvable time string")
            }
            return if (strings.size == 2) {
                Time(strings[0].toInt(), strings[1].toInt())
            } else {
                Time(
                    strings[0].toInt(),
                    strings[1].toInt(),
                    strings[2].toInt()
                )
            }
        }
    }
}

fun ClosedRange<Time>.toDateRange(): LongRange {
    val calendar = Calendar.getInstance()
    val startTime = calendar.apply {
        set(Calendar.HOUR_OF_DAY, start.hours)
        set(Calendar.MINUTE, start.minus)
        set(Calendar.SECOND, start.seconds)
    }.timeInMillis
    val endTime = calendar.apply {
        if (start > endInclusive)
            add(Calendar.DAY_OF_MONTH, 1)
        set(Calendar.HOUR_OF_DAY, endInclusive.hours)
        set(Calendar.MINUTE, endInclusive.minus)
        set(Calendar.SECOND, endInclusive.seconds)
    }.timeInMillis
    return startTime..endTime

}